import React, { Component } from 'react';
import { Form, Input, Button, message, Select, Upload } from 'antd';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import axios from './../../axios/index';
import headimgurl from './../../statics/icon/headimg.svg';
import { connect } from 'react-redux';
import './index.less';
const Option = Select.Option;
let errcount = 0;
class UserInfo extends Component {

	formRef = React.createRef();

	state = {
		loading: false,//上传头像状态
		headimgurl: sessionStorage.getItem("headimgurl"),
	};

	componentDidMount() {
		this.getUser();
	}

	//获取用户信息
	getUser = () => {
		axios.ajax({
			url: "/user/Login/getUserInfo",
			method: "get"
		}).then(res => {
			let data = res.result;
			if (data) {
				this.formRef.current.setFieldsValue({
					nick_name: data.nick_name,
					prefix: 86,
					phone: data.phone,
					mail: data.mail,
				})
			}
		})
	}

	//保存修改
	onFinish = values => {
		axios.ajax({
			url: "/User/Operate/userInfoUpdate",
			method: "post",
			data: values
		}).then(res => {
			if (res.code === 0) {
				message.success(res.msg);
				this.getUser();//重新获取数据
			} else {
				message.error("修改失败");
			}
			this.onReset();
		}).catch(err => {
			this.onReset();
		})
	};

	//重置
	onReset = () => {
		this.formRef.current.resetFields();
	};

	//上传logo大小类型限制
	beforeUpload = (file) => {
		const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
		if (!isJpgOrPng) {
			message.error('只能上传JPG/PNG图片!');
		}
		const isLt100K = file.size / 1024 < 100;
		if (!isLt100K) {
			message.error('文件大小不能超过100KB!');
		}
		return isJpgOrPng && isLt100K;
	}

	customRequest = (option) => {
		this.setState({ loading: true })
		const formData = new FormData();
		formData.append('img', option.file);
		axios.upload({
			url: "/User/Operate/userHeadImgUpload",
			data: formData
		}).then(res => {
			if (res.code === 0) {
				this.setState({
					loading: false,
				});
				message.success(res.msg);
				this.setState({ headimgurl: sessionStorage.getItem("headimgurl") + "?" + Date.now() })
				this.props.changeHeadImg(true);
				this.forceUpdate();
			} else {
				message.error("上传文件失败");
				this.setState({ loading: false })
			}
		}).catch(err => {
			this.setState({ loading: false })
		})
	}

	//头像加载失败
	logoImgError = () => {
		errcount++;
		if (errcount > 2) {
			return
		}
		this.setState({
			headimgurl
		})
	}

	render() {
		const layout = {
			labelCol: { span: 4 },
			wrapperCol: { span: 20 },
		};
		const tailLayout = {
			wrapperCol: { offset: 4, span: 20 },
		};
		const prefixSelector = (
			<Form.Item name="prefix" noStyle>
				<Select style={{ width: 70 }}>
					<Option value="86">+86</Option>
					<Option value="87">+87</Option>
				</Select>
			</Form.Item>
		);
		const uploadButton = (
			<div>
				{this.state.loading ? <LoadingOutlined /> : <PlusOutlined />}
				<div className="ant-upload-text">修改头像</div>
			</div>
		);
		const { loading, headimgurl } = this.state;
		// const url = sessionStorage.getItem("headimgurl");
		// const headimgurl = url + "?"+Date.now();
		return (
			<div className="pwd-wrap">
				<div className="pwd-content">
					<div className="title">个人资料设置</div>
					<Form {...layout}>
						<Form.Item
							label="头像"
						>
							<Upload
								listType="picture-card"
								showUploadList={false}
								customRequest={this.customRequest}
								beforeUpload={this.beforeUpload}
							>
								{loading ? uploadButton : <img src={headimgurl} alt="ligo" style={{ width: '100%' }} onError={this.logoImgError} />}
							</Upload>
						</Form.Item>
					</Form>
					<Form
						{...layout}
						ref={this.formRef}
						name="control-hooks"
						onFinish={this.onFinish}
						initialValues={{
							prefix: "86"
						}}
					>
						<Form.Item
							label="昵称"
							name="nick_name"
							hasFeedback
							validateTrigger="onChange"
							rules={[
								{ required: true, message: "请输入昵称" },
								{ max: 20, message: '昵称太长了' }
							]}
						>
							<Input placeholder="请输入昵称" autoComplete="off" />
						</Form.Item>
						<Form.Item
							label="手机号码"
							name="phone"
							hasFeedback
							validateTrigger="onChange"
							rules={[
								{ required: true, message: "请输入手机号码" },
								{ pattern: /^1[3-9]\d{9}$/g, message: "手机号码有误" }
							]}
						>
							<Input maxLength={11} addonBefore={prefixSelector} placeholder="请输入手机号码" autoComplete="off" />
						</Form.Item>
						<Form.Item
							label="邮箱"
							name="mail"
							hasFeedback
							validateTrigger="onChange"
							rules={[
								{ required: true, message: "请输入电子邮箱" },
								{ type: "email", message: "不符合电子邮箱格式" },
								{ max: 30, message: '请输入正确的邮箱' }
							]}
						>
							<Input placeholder="请输入电子邮箱" autoComplete="off" />
						</Form.Item>
						<Form.Item {...tailLayout} style={{ textAlign: "center" }}>
							<Button type="primary" htmlType="submit">
								保存
							</Button>
							<Button htmlType="button" onClick={this.onReset}>
								重置
							</Button>
						</Form.Item>
					</Form>
				</div>
			</div>
		)
	}
}

const mapDispatch = (dispatch) => {
	return {
		changeHeadImg(value) {
			dispatch({
				type: "CHANGE_HEAD_IMG",
				value
			})
		}
	}
}

export default connect(null, mapDispatch)(UserInfo);